package com.qf.controller;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.qf.entity.User;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.R;
import com.qf.util.RsaUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.UUID;



/**
 * --- 永无霸哥 ---
 *
 * @author M.rk
 * @date 2024/12/2 13:42
 * @desc
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserLoginController {

    @Autowired
    UserServiceImpl userService;

    /**
     * 系统用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody User user, HttpSession session) throws Exception {
        System.out.println("UserController.login,接收数据"+user);
        //前端加密后进行解密
        String pwd = RsaUtils.decryptByPrivateKey(user.getPassword());

        String  md5 = SecureUtil.md5(pwd);
            log.debug("加密后——————》"+md5);
            //后端加密
        user.setPassword(md5);
        User login = userService.login(user);
        System.out.println("login = " + login);
        if (login != null) {

            //登录成功，存储用户信息
            session.setAttribute("userInfo",login);

            //造假token，给前端
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", UUID.randomUUID().toString());
            return R.ok(map);
        }
        return R.fail();
    }


    @GetMapping("/Info")
    public R getUserInfo(HttpSession session){
        User info = (User) session.getAttribute("userInfo");
        System.out.println(" UserController.getUserInfo: " +info );
        return R.ok(info);

    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public R logout(HttpSession session) {
        session.invalidate();
        // TODO, 清除redis中token
        return R.ok( );
    }
}


